<template>
    <div class="user-management">
        <div class="app-container">
            <!-- 查询表单 -->
            <div class="filter-container">
                <el-form :inline="true" :model="queryParams" class="demo-form-inline">
                    <el-form-item label="账号">
                        <el-input v-model="queryParams.account" placeholder="请输入账号" clearable style="width: 200px;"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>

                    <el-form-item label="用户名">
                        <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable style="width: 200px;"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>

                    <el-form-item label="手机号">
                        <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable style="width: 200px;"
                            @keyup.enter.native="handleQuery" />
                    </el-form-item>

                    <el-form-item label="角色">
                        <el-select v-model="queryParams.roleId" placeholder="请选择角色" clearable style="width: 150px;"
                            @change="handleQuery">
                            <el-option v-for="item in roleOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="账号状态">
                        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px;"
                            @change="handleQuery">
                            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="handleQuery">
                            查询
                        </el-button>
                        <el-button icon="el-icon-refresh" @click="resetQuery">
                            重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 用户表格 -->
            <el-table v-loading="loading" height="380" :data="userList" border style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />

                <el-table-column label="用户ID" prop="id" width="80" align="center" />

                <el-table-column label="头像" width="80" align="center">
                    <template slot-scope="scope">
                        <el-avatar :size="40" :src="scope.row.avatar" :alt="scope.row.username">
                            <i class="el-icon-user-solid"></i>
                        </el-avatar>
                    </template>
                </el-table-column>

                <el-table-column label="用户名" prop="username" width="120" />

                <el-table-column label="账号" prop="account" width="120" />

                <el-table-column label="手机号" prop="phone" width="130" />

                <el-table-column label="性别" width="80" align="center">
                    <template slot-scope="scope">
                        <div style="text-align: center;">
                            <el-tag
                                :type="scope.row.gender === 1 ? 'primary' : scope.row.gender === 2 ? 'success' : 'info'"
                                size="mini">
                                {{ getGenderText(scope.row.gender) }}
                            </el-tag>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="系/学院" prop="department" width="150" show-overflow-tooltip />

                <el-table-column label="专业" prop="major" width="120" show-overflow-tooltip />

                <el-table-column label="角色" width="100" align="center">
                    <template slot-scope="scope">
                        <div style="text-align: center;">
                            <el-tag :type="getRoleTagType(scope.row.roleId)" size="mini">
                                {{ getRoleText(scope.row.roleId) }}
                            </el-tag>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="账号状态" width="100" align="center">
                    <template slot-scope="scope">
                        <div style="text-align: center;">
                            <el-tag :type="getStatusTagType(scope.row.status)" size="mini">
                                {{ getStatusText(scope.row.status) }}
                            </el-tag>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="创建时间" prop="createTime" width="160" align="center">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="240" align="center" fixed="right">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-key" @click="handleResetPassword(scope.row)">
                            重置密码
                        </el-button>
                        <el-button v-if="scope.row.status === 0" size="mini" type="text" icon="el-icon-check"
                            @click="handleApproval(scope.row)" style="color: #67c23a">
                            审批
                        </el-button>
                        <el-button v-if="scope.row.status === 1" size="mini" type="text" icon="el-icon-close"
                            @click="handleToggleStatus(scope.row, 2)" style="color: #f56c6c">
                            禁用
                        </el-button>
                        <el-button v-if="scope.row.status === 2" size="mini" type="text" icon="el-icon-check"
                            @click="handleToggleStatus(scope.row, 1)" style="color: #67c23a">
                            启用
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页器 -->
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo"
                :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
    </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import userApi from '@/api/user'


export default {
    name: 'UserManagement',
    components: {
        Pagination
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 用户表格数据
            userList: [],
            // 查询参数
            queryParams: {
                pageNo: 1,
                pageSize: 10,
                account: undefined,
                username: undefined,
                phone: undefined,
                roleId: undefined,
                status: undefined
            },
            // 角色选项
            roleOptions: [
                { value: '1', label: '管理员' },
                { value: '2', label: '教师' },
                { value: '3', label: '学生' }
            ],
            // 状态选项
            statusOptions: [
                { value: 0, label: '待审核' },
                { value: 1, label: '正常' },
                { value: 2, label: '禁用' }
            ]
        }
    },
    created() {
        this.getList();
    },
    methods: {
        /** 查询用户列表 */
        async getList() {
            try {
                this.loading = true
                let res = await userApi.getUserList(this.queryParams);
                this.userList = res.data.records || res.data.list || [];
                this.total = res.data.total || 0;
            } catch (error) {
                console.log("获取用户列表失败:", error);
            } finally {
                this.loading = false
            }
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNo = 1
            this.getList()
        },

        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                pageNo: 1,
                pageSize: 10,
                account: undefined,
                username: undefined,
                phone: undefined,
                roleId: undefined,
                status: undefined
            }
            this.handleQuery()
        },

        /** 多选框选中数据 */
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        /** 查看用户详情 */
        handleView(row) {
            this.$message.info(`查看用户：${row.username}`)
        },


        /** 审批用户 */
        async handleApproval(row) {
            try {
                await this.$confirm(`确认审批通过用户"${row.username}"吗？`, '审批用户', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })

                const loading = this.$loading({
                    lock: true,
                    text: '正在审批...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                })

                try {
                    await userApi.approvalUser(row.id)
                    this.$message.success('审批成功')
                    this.getList()
                } catch (apiError) {
                    console.log("审批API调用失败:", apiError);
                } finally {
                    loading.close()
                }
            } catch (error) {
                // 用户取消确认
                if (error !== 'cancel') {
                    console.log("审批操作错误:", error);
                }
            }
        },

        /** 重置密码 */
        async handleResetPassword(row) {
            try {
                await this.$confirm(`确认重置用户"${row.username}"的密码吗？`, '重置密码', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })

                // 显示加载状态
                const loading = this.$loading({
                    lock: true,
                    text: '正在重置密码...',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                })

                try {
                    await userApi.resetPassword(row.id)
                    this.$message.success('密码重置成功')
                    this.getList()
                } catch (apiError) {
                    console.log("重置密码API调用失败:", apiError);
                    this.$message.error('重置密码失败：' + (apiError.message || '网络错误'))
                } finally {
                    loading.close()
                }
            } catch (error) {
                // 用户取消确认或其他错误
                if (error !== 'cancel') {
                    console.log("重置密码操作错误:", error);
                }
            }
        },

        /** 切换用户状态（启用/禁用） */
        async handleToggleStatus(row, status) {
            const statusText = status === 1 ? '启用' : '禁用'
            try {
                await this.$confirm(`确认${statusText}用户"${row.username}"吗？`, `${statusText}用户`, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })

                const loading = this.$loading({
                    lock: true,
                    text: `正在${statusText}...`,
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                })

                try {
                    await userApi.updateStatus(status, row.id)
                    this.$message.success(`${statusText}成功`)
                    this.getList()
                } catch (apiError) {
                    console.log(`${statusText}API调用失败:`, apiError);
                    this.$message.error(`${statusText}失败：` + (apiError.message || '网络错误'))
                } finally {
                    loading.close()
                }
            } catch (error) {
                // 用户取消确认
                if (error !== 'cancel') {
                    console.log(`${statusText}操作错误:`, error);
                }
            }
        },


        /** 获取性别文本 */
        getGenderText(gender) {
            const genderMap = {
                0: '未知',
                1: '男',
                2: '女'
            }
            return genderMap[gender] || '未知'
        },

        /** 获取角色文本 */
        getRoleText(roleId) {
            const role = this.roleOptions.find(item => item.value === String(roleId))
            return role ? role.label : '未知'
        },

        /** 获取角色标签类型 */
        getRoleTagType(roleId) {
            const typeMap = {
                '1': 'success', // 教师
                '2': 'primary', // 学生
                '3': 'danger'   // 管理员
            }
            return typeMap[String(roleId)] || 'info'
        },

        /** 获取状态文本 */
        getStatusText(status) {
            const statusMap = {
                0: '待审核',
                1: '正常',
                2: '禁用'
            }
            return statusMap[status] || '未知'
        },

        /** 获取状态标签类型 */
        getStatusTagType(status) {
            const typeMap = {
                0: 'warning', // 待审核
                1: 'success', // 正常
                2: 'danger'   // 禁用
            }
            return typeMap[status] || 'info'
        },

        /** 时间格式化 */
        parseTime(time) {
            if (!time) return '-'
            const date = new Date(time)
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            })
        },


    }
}
</script>

<style lang="scss" scoped>
.user-management {
    .app-container {
        padding: 20px;
    }

    .filter-container {
        padding: 10px 0;
        margin-bottom: 20px;
        background: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);

        .el-form {
            padding: 20px;
        }
    }

    .el-table {
        background: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
    }
}
</style>
